package com.example.service.impl;


import com.example.mapper.DeptMapper;
import com.example.mapper.EmpMapper;
import com.example.pojo.Dept;
import com.example.pojo.Student;
import com.example.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    /**
     * 查询所有部门
     *
     * @return
     */
    @Override
    public List<Dept> findAll() {

        return deptMapper.findAll();
    }

    /**
     * 根据id查询部门
     *
     * @param id
     * @return
     */
    @Override
    public Dept getById(Integer id) {
        Dept dept = deptMapper.getById(id);

        return dept;
    }

    /**
     * 根据id删除部门
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) throws Exception {
        //检查部门是否还有所属员工
        List<Student> list = empMapper.getByDeptId(id);
        if (!list.isEmpty()) {
            throw new Exception("部门下有员工，不能删除");
        }

        deptMapper.deleteById(id);
    }

    /**
     * 新增部门
     *
     * @param dept
     */
    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        deptMapper.insert(dept);
    }

    /**
     * 根据部门名称查询部门
     *
     * @param name
     * @return
     */
    @Override
    public Dept findByName(String name) {

        return deptMapper.findByName(name);
    }

    /**
     * 根据ID修改部门
     *
     * @param dept
     */
    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
